package fair.test;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.junit.Test;

import java.io.UnsupportedEncodingException;

/**
 * @author fair_wu
 * @version v1.0
 * @date 2021-01-25 下午 21:05
 */
public class QiNiu {
    //使用七牛云提供的SDK实现将本地图片上传到七牛云云服务器

    /**
     * 上传文件
     */
    @Test
    public void test1(){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "mppj5bPWePj2eieo_wAN1FtGyFrZe1PhU2wsV6Tq";
        String secretKey = "yPypri8jZHfziZCsGONnB9SyPm8ObI-IP-yKi558";
        String bucket = "health-fair";
        String localFilePath = "D:\\javaProject\\project\\health_parent\\图片资源\\03a36073-a140-4942-9b9b-712cecb144901.jpg";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    /**
     * 删除文件
     */
    @Test
    public void test2(){
        Configuration cfg = new Configuration(Region.region2());
        //...生成上传凭证，然后准备上传
        String accessKey = "mppj5bPWePj2eieo_wAN1FtGyFrZe1PhU2wsV6Tq";
        String secretKey = "yPypri8jZHfziZCsGONnB9SyPm8ObI-IP-yKi558";
        String bucket = "health-fair";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = "setmeal1.jpg";
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
        }catch (QiniuException ex) {
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }
}
